package com.hezuti.common.url;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Component;

import com.hezuti.common.url.dispatch.IpObject;
import com.hezuti.common.url.dispatch.RequestDispatcher;
import com.hezuti.common.utils.FormatUtil;


/**
 * host 管理类
 * 
 * @author Administrator
 *
 */
@Component
public class HostManager {
    private static Map<String, RequestDispatcher> hostmap = new HashMap<String, RequestDispatcher>();
    private static Map<String, String>	    urimap  = new HashMap<String, String>();
    private static HostManager		    _self   = new HostManager();

    private HostManager() {
    }

    public static HostManager newInstance() {
	return _self;
    }

    public String getHost(String key) {
	RequestDispatcher dispatcher = hostmap.get(key);
	if (dispatcher != null) {
	    IpObject ip = (IpObject) dispatcher.getObject();
	    return "http://" + ip.getIp() + ":" + ip.getPort();
	} else
	    return null;
    }

    public String getUri(String key) {
	return urimap.get(key);
    }

    public String addHost(String key, String host) {
	String[] hosts = host.split(",");
	List<IpObject> hostList = new ArrayList<IpObject>();
	for (int i = 0; i < hosts.length; i++) {
	    String[] data = hosts[i].split(":");
		IpObject ip = new IpObject();
		
		ip.setIp(data[0]);
		if(data.length>=2)//判断是否配置 端口号
		    ip.setPort(FormatUtil.parseInt(data[1], 80));
		else
		    ip.setPort(80);
		if(data.length>=3)//判断是否有权重
		ip.setWeight(FormatUtil.parseInt(data[2], 0));
		
		hostList.add(ip);
	}
	RequestDispatcher dispatcher = new RequestDispatcher(hostList, 0);
	hostmap.put(key, dispatcher);// 将广告 对应host放入 hostmap中
	return host;
    }

    public String addUri(String key, String uri) {
	urimap.put(key, uri);
	return uri;
    }
}
